package com.deliveryservicesystem.service.crud.impl;

import com.deliveryservicesystem.app.exceptions.NonexistentEntityException;
import com.deliveryservicesystem.app.exceptions.PreexistingEntityException;
import com.deliveryservicesystem.dataaccess.PersistenceDbManager;
import com.deliveryservicesystem.model.Product;
import com.deliveryservicesystem.model.Subscription;
import com.deliveryservicesystem.model.Supplier;
import com.deliveryservicesystem.service.crud.ProductCrudService;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 * File Name: ProductCrudServiceImpl.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.service.crud.impl
 * Author: Lance
 * Date: Jun 20, 2012
 * Editor:
 */
public class ProductCrudServiceImpl implements ProductCrudService
{

    private static final long serialVersionUID = 1L;
    private EntityManagerFactory emf = null;

    /**
     * Create the new CRUD service. Internally setting the EntityManagerFactory
     * using database details from database properties
     */
    public ProductCrudServiceImpl()
    {
        PersistenceDbManager persistenceManager = PersistenceDbManager.getInstance();
        this.emf = persistenceManager.getEntityManagerFactory();
    }

    @Override
    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    @Override
    public void create(Product product) throws PreexistingEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Supplier supplierNo = product.getSupplierNo();
            if (supplierNo != null)
            {
                supplierNo = em.getReference(supplierNo.getClass(), supplierNo.getSupplierNo());
                product.setSupplierNo(supplierNo);
            }
            Subscription subscriptionNo = product.getSubscriptionNo();
            if (subscriptionNo != null)
            {
                subscriptionNo = em.getReference(subscriptionNo.getClass(), subscriptionNo.getSubscriptionNo());
                product.setSubscriptionNo(subscriptionNo);
            }
            em.persist(product);
            if (supplierNo != null)
            {
                supplierNo.getProductList().add(product);
                supplierNo = em.merge(supplierNo);
            }
            if (subscriptionNo != null)
            {
                subscriptionNo.getProductList().add(product);
                subscriptionNo = em.merge(subscriptionNo);
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            if (findById(product.getProductNo()) != null)
            {
                throw new PreexistingEntityException("Product " + product + " already exists.", ex);
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void edit(Product product) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Product persistentProduct = em.find(Product.class, product.getProductNo());
            Supplier supplierNoOld = persistentProduct.getSupplierNo();
            Supplier supplierNoNew = product.getSupplierNo();
            Subscription subscriptionNoOld = persistentProduct.getSubscriptionNo();
            Subscription subscriptionNoNew = product.getSubscriptionNo();
            if (supplierNoNew != null)
            {
                supplierNoNew = em.getReference(supplierNoNew.getClass(), supplierNoNew.getSupplierNo());
                product.setSupplierNo(supplierNoNew);
            }
            if (subscriptionNoNew != null)
            {
                subscriptionNoNew = em.getReference(subscriptionNoNew.getClass(), subscriptionNoNew.getSubscriptionNo());
                product.setSubscriptionNo(subscriptionNoNew);
            }
            product = em.merge(product);
            if (supplierNoOld != null && !supplierNoOld.equals(supplierNoNew))
            {
                supplierNoOld.getProductList().remove(product);
                supplierNoOld = em.merge(supplierNoOld);
            }
            if (supplierNoNew != null && !supplierNoNew.equals(supplierNoOld))
            {
                supplierNoNew.getProductList().add(product);
                supplierNoNew = em.merge(supplierNoNew);
            }
            if (subscriptionNoOld != null && !subscriptionNoOld.equals(subscriptionNoNew))
            {
                subscriptionNoOld.getProductList().remove(product);
                subscriptionNoOld = em.merge(subscriptionNoOld);
            }
            if (subscriptionNoNew != null && !subscriptionNoNew.equals(subscriptionNoOld))
            {
                subscriptionNoNew.getProductList().add(product);
                subscriptionNoNew = em.merge(subscriptionNoNew);
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = product.getProductNo();
                if (findById(id) == null)
                {
                    throw new NonexistentEntityException("The product with id " + id + " no longer exists.");
                }
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Product product;
            try
            {
                product = em.getReference(Product.class, id);
                product.getProductNo();
            }
            catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The product with id " + id + " no longer exists.", enfe);
            }
            Supplier supplierNo = product.getSupplierNo();
            if (supplierNo != null)
            {
                supplierNo.getProductList().remove(product);
                supplierNo = em.merge(supplierNo);
            }
            Subscription subscriptionNo = product.getSubscriptionNo();
            if (subscriptionNo != null)
            {
                subscriptionNo.getProductList().remove(product);
                subscriptionNo = em.merge(subscriptionNo);
            }
            em.remove(product);
            em.getTransaction().commit();
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public List<Product> findEntities()
    {
        return findProductEntities(true, -1, -1);
    }

    @Override
    public List<Product> findEntities(int maxResults, int firstResult)
    {
        return findProductEntities(false, maxResults, firstResult);
    }

    private List<Product> findProductEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Product.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public Product findById(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Product.class, id);
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public int count()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Product> rt = cq.from(Product.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        }
        finally
        {
            em.close();
        }
    }
}
